package com.zlkj.ssm.shop.common.tools;

import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.mail.util.MailSSLSocketFactory;
import com.zlkj.ssm.shop.core.cache.provider.SystemManager;
import com.zlkj.ssm.shop.front.entity.Account;

/**
 * 发送邮件工具类 http://blog.csdn.net/ghsau/article/details/17909093 *
 */
public class MailUtil {
	private static final Logger logger = LoggerFactory.getLogger(MailUtil.class);

	// public static void main(String[] args) {
	// MailUtil mail = new MailUtil("724762704@qq.com", "724762704@qq.com",
	// "jywavjjxqywabdji", "smtp.qq.com", "标题");
	// mail.attachfile("c:\\offline_FtnInfo.txt");
	// mail.attachfile("c:\\log.log");
	// mail.startSend("aaa", "aaaaaaa");
	// }

	String to = null;// 收件人
	String from = null;// 发件人
	String password = null;// 密码或者授权码
	String host = null;// smtp服务器
	String filename = null;//
	String subject = null;// 主题
	Vector<String> file = new Vector<String>();// 用于保存发送附件的文件名的集合

	/**
	 * 初始化邮箱信息(自定义)
	 * 
	 * @param to
	 *            接收人
	 * @param from
	 *            发送人
	 * @param password
	 *            授权码
	 * @param smtpServer
	 *            smtp服务器
	 * @param subject
	 *            主题
	 */
	public MailUtil(String to, String from, String password, String smtpServer, String subject) {
		this.to = to;
		this.from = from;
		this.password = password;
		this.host = smtpServer;
		this.subject = subject;
	}

	/**
	 * 初始化邮箱信息(从配置文件读取发送人 授权码 smtp服务器)
	 * 
	 * @param to
	 *            邮件接收人
	 */
	public MailUtil(String to) {
		this.to = to;
		this.from = SystemManager.getInstance().getProperty("from_email_account");
		this.password = SystemManager.getInstance().getProperty("from_email_password");
		this.host = SystemManager.getInstance().getProperty("from_eamil_smtpServer");
	}

	/**
	 * 该方法用于收集附件名
	 * 
	 * @param fname
	 */
	public void attachfile(String fName) {
		file.addElement(fName);
	}

	/**
	 * 开始发送信件的方法
	 * 
	 * @param emailTitle
	 *            邮箱标题
	 * @param emailContent
	 *            邮箱内容
	 * @return
	 */
	public boolean startSend(String emailTitle, String emailContent) {
		if (StringUtils.isBlank(emailContent)) {
			logger.error("邮件内容不能为空！");
			return false;
		}

		try {
			if (StringUtils.isBlank(emailContent)) {
				throw new NullPointerException("发送的内容不能为空！");
			}
			// 创建Properties对象
			Properties props = System.getProperties();
			// props.setProperty("mail.debug", "true");// 开启debug调试
			props.setProperty("mail.smtp.auth", "true");// 发送服务器需要身份验证
			props.setProperty("mail.host", "smtp.qq.com");
			props.setProperty("mail.transport.protocol", "smtp");// 发送邮件协议名称
			
			// 开启ssl加密，如果没有ssl加密，会报530错误
			MailSSLSocketFactory sf = new MailSSLSocketFactory();
			sf.setTrustAllHosts(true);
			props.put("mail.smtp.ssl.enable", "true");
			props.put("mail.smtp.ssl.socketFactory", sf);

			// 得到默认的对话对象
			Session session = Session.getInstance(props, new PopupAuthenticator(this.from, this.password));

			// 创建一个消息，并初始化该消息的各项元素
			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(from));
			InternetAddress[] address = { new InternetAddress(to) };
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setSubject(emailTitle);

			// 后面的BodyPart将加入到此处创建的Multipart中
			Multipart mp = new MimeMultipart("subtype");

			// 添加HTML正文
			BodyPart htmlBody = new MimeBodyPart();
			MimeMultipart htmlContent = new MimeMultipart("related");
			BodyPart msgContent = new MimeBodyPart();
			htmlContent.addBodyPart(msgContent);
			msgContent.setContent(emailContent, "text/html;charset=utf-8");
			htmlBody.setContent(htmlContent);
			mp.addBodyPart(htmlBody);

			// 利用枚举器方便的遍历集合
			Enumeration<String> efile = file.elements();
			while (efile.hasMoreElements()) {
				MimeBodyPart mbp = new MimeBodyPart();
				filename = efile.nextElement().toString();// 选择出每一个附件名
				FileDataSource fds = new FileDataSource(filename);
				mbp.setDataHandler(new DataHandler(fds));// 得到附件本身并至入BodyPart
				mbp.setFileName(fds.getName());// 得到文件名同样至入BodyPart
				mp.addBodyPart(mbp);
			}
			file.removeAllElements();
			msg.setContent(mp);// Multipart加入到信件
			msg.setSentDate(new Date());// 设置信件头的发送日期
			Transport.send(msg);// 发送信件
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * Authenticator(java mail里面的包)，不要引成net的包了
	 */
	class PopupAuthenticator extends Authenticator {
		String username = null;
		String password = null;

		public PopupAuthenticator(String user, String pass) {
			username = user;
			password = pass;
		}

		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(username, password);
		}
	}

	/**
	 * 忘记密码的HTML
	 * 
	 * @return
	 */
	public static String getForgetHtml(Account account, int pageType) {
		StringBuilder buff = new StringBuilder();
		// buff.append("http://127.0.0.1:8082/mybbs/forget.html?account=" +
		// account.getAccount() + "&sign=" + account.getSign() + "&pageType=" +
		// pageType);
		// buff.append("http://127.0.0.1:80/mybbs/forget.html?account=" +
		// account.getAccount() + "&sign=" + account.getSign() + "&pageType=" +
		// pageType);

		return buff.toString();
	}
}
